{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "931f661d",
   "metadata": {},
   "source": [
    "# 网格搜索和更多kNN中的超参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7fc86265",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn import datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "22e0129b",
   "metadata": {},
   "outputs": [],
   "source": [
    "digits = datasets.load_digits()\n",
    "X = digits.data\n",
    "y = digits.target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5446784e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=666)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "bf22ea7b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9916666666666667"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "sk_knn_clf = KNeighborsClassifier(n_neighbors=4, weights=\"uniform\")\n",
    "sk_knn_clf.fit(X_train, y_train)\n",
    "sk_knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8eb6c3df",
   "metadata": {},
   "source": [
    "## Grid Search"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffc937f6",
   "metadata": {},
   "source": [
    "先定义参数，把可能的组合放入字典中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "42360537",
   "metadata": {},
   "outputs": [],
   "source": [
    "param_grid = [\n",
    "    {\n",
    "        'weights': ['uniform'], \n",
    "        'n_neighbors': [i for i in range(1, 11)]\n",
    "    },\n",
    "    {\n",
    "        'weights': ['distance'],\n",
    "        'n_neighbors': [i for i in range(1, 11)], \n",
    "        'p': [i for i in range(1, 6)]\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b9cf52bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "knn_clf = KNeighborsClassifier()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "83f64f45",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "grid_search = GridSearchCV(knn_clf, param_grid)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "53718502",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 1min 41s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "GridSearchCV(estimator=KNeighborsClassifier(),\n",
       "             param_grid=[{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n",
       "                          'weights': ['uniform']},\n",
       "                         {'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n",
       "                          'p': [1, 2, 3, 4, 5], 'weights': ['distance']}])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "grid_search.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac4d90a9",
   "metadata": {},
   "source": [
    "返回最佳分类器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "f38ee84f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "KNeighborsClassifier(n_neighbors=1)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grid_search.best_estimator_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2eee728",
   "metadata": {},
   "source": [
    "返回最佳分类器对应的准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "866e8180",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9860820751064653"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grid_search.best_score_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03781095",
   "metadata": {},
   "source": [
    "返回最佳分类器的参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "add45d29",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'n_neighbors': 1, 'weights': 'uniform'}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grid_search.best_params_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "efa12735",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9833333333333333"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn_cf = grid_search.best_estimator_\n",
    "knn_cf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "b494f284",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fitting 5 folds for each of 60 candidates, totalling 300 fits\n",
      "Wall time: 47.1 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "GridSearchCV(estimator=KNeighborsClassifier(), n_jobs=-1,\n",
       "             param_grid=[{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n",
       "                          'weights': ['uniform']},\n",
       "                         {'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n",
       "                          'p': [1, 2, 3, 4, 5], 'weights': ['distance']}],\n",
       "             verbose=6)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "grid_search = GridSearchCV(knn_clf, param_grid, n_jobs=-1, verbose=6)\n",
    "grid_search.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f6f3c5c3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
